package com.tan.websocket.event;

import cn.hutool.core.util.ObjectUtil;
import com.tan.common.dto.chat.ChatInfoDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @author Tan
 * @description 事件发布者
 * @date 2025/1/28
 */
@Slf4j
public class ChatPublisher {

    private final Map<Class<?>, List<ChatEventListener<?>>> subscribers = new HashMap<>();

    /**
     * 注册监听器
     */
    public <T> void registerListener(Class<T> eventType, ChatEventListener<T> listener) {
        subscribers.computeIfAbsent(eventType, k -> new CopyOnWriteArrayList<>())
                .add(listener);
    }

    /**
     * 取消注册
     */
    public <T> void unsubscribe(Class<T> eventType, ChatEventListener<T> listener) {
        List<ChatEventListener<?>> list = subscribers.get(eventType);
        if (list != null) {
            list.remove(listener);
        }
    }

    /**
     * 利用 eventType 进行安全分发
     */
    public <T> void sendMessage(T event) {
        Class<?> eventType = event.getClass();
        List<ChatEventListener<?>> listeners = subscribers.get(eventType);
        if (listeners != null && !listeners.isEmpty()) {
            List<ChatEventListener<?>> copy = new ArrayList<>(listeners);
            for (ChatEventListener<?> listener : copy) {
                try {
                    ((ChatEventListener<T>) listener).onMessageReceived(event);
                } catch (Exception e) {
                    log.info("处理事件时发生错误: {}", ExceptionUtils.getStackTrace(e));
                    e.printStackTrace();
                }
            }
        }
    }

}
